<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      border: 1px solid;
    }
  </style>
</head>

<body>
  <canvas class="box" width="400" height="400"></canvas>
  <script>
    let imgArr = ["https://img1.baidu.com/it/u=204850541,579029014&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400", "https://img2.baidu.com/it/u=3761681979,4062137766&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400", "https://img2.baidu.com/it/u=4046706485,516958200&fm=253&fmt=auto&app=120&f=JPEG?w=400&h=400", "https://img2.baidu.com/it/u=3731242143,2511214305&fm=253&fmt=auto&app=138&f=PNG?w=400&h=400"];
    // 定义一个图片加载函数
    function loadImg (imgArr) {
      return new Promise(resolve => {
        let count = 0;
        // 收集加载完毕的图片对象，存放在对象数组里
        let resArr = [];
        imgArr.forEach(src => {
          let imgEle = new Image();
          imgEle.src = src;
          imgEle.onload = function () {
            resArr.push(this);
            count++;
            if (count === imgArr.length) {
              // console.log(resArr);
              // 通过resolve返还结果
              resolve(resArr);
            }
          }
        })
      })
    }
    let canvas = document.querySelector(".box");
    let ctx = canvas.getContext("2d");
    // 给三张图片做预加载
    loadImg(imgArr).then(res => {
      console.log(res);
      ctx.drawImage(res[0], 0, 0, 200, 200);
      ctx.drawImage(res[1], 200, 0, 200, 200);
      ctx.drawImage(res[2], 0, 200, 200, 200);
      ctx.drawImage(res[3], 200, 200, 200, 200);
    })
  </script>
</body>

</html>